import React, { useState } from 'react';
import { Button, Input, Select, Space, Tabs, message } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import JSONInput from 'react-json-editor-ajrm';
import locale from 'react-json-editor-ajrm/locale/en';

const { TabPane } = Tabs;
const { TextArea } = Input;

interface ApiTestRequest {
  url: string;
  method: string;
  headers: Record<string, string>;
  params: Record<string, string>;
  body: any;
}

interface ApiTestResponse {
  code: number;
  data: any;
  msg: string;
}

const ApiTest: React.FC = () => {
  const [url, setUrl] = useState<string>('');
  const [method, setMethod] = useState<string>('GET');
  const [headers, setHeaders] = useState<[string, string][]>([['', '']]);
  const [params, setParams] = useState<[string, string][]>([['', '']]);
  const [requestBody, setRequestBody] = useState<any>({});
  const [response, setResponse] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  const handleHeaderChange = (index: number, key: string, value: string) => {
    const newHeaders = [...headers];
    newHeaders[index] = [key, value];
    if (index === headers.length - 1 && key !== '' && value !== '') {
      newHeaders.push(['', '']);
    }
    setHeaders(newHeaders);
  };

  const handleParamChange = (index: number, key: string, value: string) => {
    const newParams = [...params];
    newParams[index] = [key, value];
    if (index === params.length - 1 && key !== '' && value !== '') {
      newParams.push(['', '']);
    }
    setParams(newParams);
  };

  const handleSend = async () => {
    try {
      setLoading(true);

      const headersObj = headers.reduce((acc, [key, value]) => {
        if (key && value) acc[key] = value;
        return acc;
      }, {} as Record<string, string>);

      const paramsObj = params.reduce((acc, [key, value]) => {
        if (key && value) acc[key] = value;
        return acc;
      }, {} as Record<string, string>);

      const request: ApiTestRequest = {
        url,
        method,
        headers: headersObj,
        params: paramsObj,
        body: requestBody
      };

      const res = await fetch('/api/debug/apitest', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': localStorage.getItem('token') || ''
        },
        body: JSON.stringify(request)
      });

      const data: ApiTestResponse = await res.json();
      
      if (data.code === 200) {
        setResponse(JSON.stringify(data.data, null, 2));
      } else {
        message.error(data.msg || '请求失败');
        setResponse(JSON.stringify(data, null, 2));
      }
    } catch (error) {
      message.error('请求发送失败');
      console.error('Error sending request:', error);
      setResponse(error instanceof Error ? error.message : String(error));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* URL和方法选择 */}
        <Space style={{ width: '100%' }}>
          <Select 
            value={method} 
            onChange={setMethod}
            style={{ width: 100 }}
          >
            {['GET', 'POST', 'PUT', 'DELETE'].map(m => (
              <Select.Option key={m} value={m}>{m}</Select.Option>
            ))}
          </Select>
          <Input 
            placeholder="Enter URL" 
            value={url} 
            onChange={e => setUrl(e.target.value)}
            style={{ flex: 1 }}
          />
          <Button 
            type="primary" 
            icon={<SendOutlined />} 
            onClick={handleSend}
            loading={loading}
          >
            Send
          </Button>
        </Space>

        {/* 请求配置选项卡 */}
        <Tabs defaultActiveKey="params">
          <TabPane tab="Params" key="params">
            {params.map(([key, value], index) => (
              <Space key={index} style={{ marginBottom: 8 }}>
                <Input
                  placeholder="Key"
                  value={key}
                  onChange={e => handleParamChange(index, e.target.value, value)}
                />
                <Input
                  placeholder="Value"
                  value={value}
                  onChange={e => handleParamChange(index, key, e.target.value)}
                />
              </Space>
            ))}
          </TabPane>
          
          <TabPane tab="Headers" key="headers">
            {headers.map(([key, value], index) => (
              <Space key={index} style={{ marginBottom: 8 }}>
                <Input
                  placeholder="Key"
                  value={key}
                  onChange={e => handleHeaderChange(index, e.target.value, value)}
                />
                <Input
                  placeholder="Value"
                  value={value}
                  onChange={e => handleHeaderChange(index, key, e.target.value)}
                />
              </Space>
            ))}
          </TabPane>
          
          <TabPane tab="Body" key="body">
            <JSONInput
              id="json-editor"
              placeholder={requestBody}
              locale={locale}
              height="300px"
              width="100%"
              onChange={(value: any) => {
                if (value.jsObject) {
                  setRequestBody(value.jsObject);
                }
              }}
            />
          </TabPane>
        </Tabs>

        {/* 响应结果 */}
        <div>
          <h3>Response</h3>
          <TextArea
            value={response}
            autoSize={{ minRows: 4, maxRows: 20 }}
            readOnly
          />
        </div>
      </Space>
    </div>
  );
};

export default ApiTest; 